package controller

import (
	"ais-go/app/models"
	"ais-go/app/tools"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type portCtl struct {
	db *gorm.DB
}

var Port = portCtl{}

// GetPortListByPage 获取港口列表
func (ctl *portCtl) GetPortListByPage(c *gin.Context) {
	ctl.db = models.Db
	var portList []models.Gangkou
	var count int64
	page := c.Query("page")
	pageInt := tools.StrToInt(page)
	pageSize := c.Query("pageSize")
	pageSizeInt := tools.StrToInt(pageSize)
	ctl.db.Model(&models.Gangkou{}).Count(&count)
	//根据port_name排序
	ctl.db.Order("port_name").Limit(pageSizeInt).Offset((pageInt - 1) * pageSizeInt).Find(&portList)
	tools.SuccessResp(c, "获取成功", gin.H{
		"portList": portList,
		"count":    count,
	})
}

func (ctl *portCtl) GetPortListByCountryName(c *gin.Context) {
	ctl.db = models.Db
	var portList []models.Gangkou
	var count int64
	page := c.Query("page")
	pageInt := tools.StrToInt(page)
	pageSize := c.Query("pageSize")
	pageSizeInt := tools.StrToInt(pageSize)
	countryName := c.Query("countryName")
	ctl.db.Model(&models.Gangkou{}).Where("country_cn = ?", countryName).Count(&count)
	ctl.db.Where("country_cn = ?", countryName).Order("port_name").Limit(pageSizeInt).Offset((pageInt - 1) * pageSizeInt).Find(&portList)
	tools.SuccessResp(c, "获取成功", gin.H{
		"portList": portList,
		"count":    count,
	})
}

// GetPortListByPortName 根据port_name模糊查询
func (ctl *portCtl) GetPortListByPortName(c *gin.Context) {
	ctl.db = models.Db
	var portList []models.Gangkou
	var count int64
	page := c.Query("page")
	pageInt := tools.StrToInt(page)
	pageSize := c.Query("pageSize")
	pageSizeInt := tools.StrToInt(pageSize)
	portName := c.Query("portName")
	ctl.db.Model(&models.Gangkou{}).Where("port_name like ?", "%"+portName+"%").Count(&count)
	ctl.db.Where("port_name like ?", "%"+portName+"%").Order("port_name").Limit(pageSizeInt).Offset((pageInt - 1) * pageSizeInt).Find(&portList)
	tools.SuccessResp(c, "获取成功", gin.H{
		"portList": portList,
		"count":    count,
	})
}

// 获取所有国家
func (ctl *portCtl) GetCountryList(c *gin.Context) {
	ctl.db = models.Db
	var countryList []models.Gangkou
	ctl.db.Model(&models.Gangkou{}).Select("country_cn").Group("country_cn").Find(&countryList)
	tools.SuccessResp(c, "获取成功", countryList)
}

// 根据国家获取所有港口
func (ctl *portCtl) GetPortListByCountry(c *gin.Context) {
	ctl.db = models.Db
	var portList []models.Gangkou
	country := c.Query("country")
	ctl.db.Where("country_cn = ?", country).Find(&portList)
	tools.SuccessResp(c, "获取成功", portList)
}

type CountryAndCount struct {
	CountryCn string `json:"country_cn"`
	Count     int    `json:"count"`
}

// 获取港口数量前8的国家和数量
func (ctl *portCtl) GetCountryAndCount(c *gin.Context) {
	ctl.db = models.Db
	var countryList []CountryAndCount
	ctl.db.Model(&models.Gangkou{}).Select("country_cn,count(*) as count").Group("country_cn").Order("count desc").Limit(8).Find(&countryList)
	tools.SuccessResp(c, "获取成功", countryList)
}
